package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SuppliersIdEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.europe.EuropeBrand;
import com.atmilan.quartz.model.entity.europe.EuropeProduct;
import com.atmilan.quartz.model.entity.europe.EuropeProductSku;
import com.atmilan.quartz.model.entity.europe.EuropeProductSkuMerged;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceEuropeProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 欧洲商品构建
     * @Description:  
     * @author daigb 
     * @param @param europeProduct
     * @param @return
     * @return StoreProductCrmebRequest
     * @throws
     */
    public StoreProductCrmebRequest buildEuropeProduct(EuropeProduct europeProduct, Map<String, EuropeBrand> europeBrandMap, String rateFloat, String rate, String rateCost) {
        BigDecimal price = europeProduct.getPrice();
        PriceResult priceResult = priceUtil.eur2Rmb(price);
        BigDecimal adjustPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(priceResult.getPrice()), rate);
        BigDecimal adjustcost = PriceUtil.calePrice(priceResult.getPrice(), rateCost);
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, europeProduct.getBrandId())
                .eq(StoreBrand :: getType, ProductTypeEnum.EUROPE)
                .last("LIMIT 1")
                );
        StoreBrand storeBrand = null;
        if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }
        // 处理单独品牌价格(无法做成配置的)
        if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
            adjustPrice = PriceUtil.calePrice(priceUtil.eur2Rmb(price).getPrice(), "0.65");
        }
        
        List<EuropeProductSkuMerged> list = europeProduct.getSkuMergedList();
        // 规格处理
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);

        BigDecimal referencePrice = europeProduct.getReferencePrice();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

        List<String> valueList = new ArrayList<>();
        List<String> valueColorList = new ArrayList<>();
        
        for(EuropeProductSkuMerged esm : list) {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setImage(europeProduct.getGoodsImg());
            storeProductAttrValueRequest.setPrice(adjustPrice);
            storeProductAttrValueRequest.setOtPrice(referencePrice);
            storeProductAttrValueRequest.setCost(adjustcost);
            storeProductAttrValueRequest.setStock(esm.getStock());
            storeProductAttrValueRequest.setSourceSkuId(esm.getSkuId());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            List<String> suk = new ArrayList<String>();
            if (StringUtils.isNotBlank(esm.getColor())) {
                linkedMap.put("颜色", esm.getColor());
                if (!valueColorList.contains(esm.getColor())) {
                    valueColorList.add(esm.getColor());
                }
                suk.add(esm.getColor());
            }
            if (StringUtils.isNotBlank(esm.getSize())) {
                linkedMap.put("尺寸", esm.getSize());
                if (!valueList.contains(esm.getSize())) {
                    valueList.add(esm.getSize());
                }
                suk.add(esm.getSize());
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            storeProductAttrValueRequest.setTempId(3);
            attrValueList.add(storeProductAttrValueRequest);
        }
        if (CollectionUtils.isNotEmpty(valueColorList)) {
            storeProductAttrColor.setAttrValues(String.join(",", valueColorList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }

        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        productRequest.setExchangeRate(priceResult.getExchangeRate());
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        productRequest.setMerId(CrmebMerchantEnums.EUROPE.getMerchantId());
        productRequest.setKeyword(europeProduct.getCode());
        List<EuropeProductSku> europeProductSku = europeProduct.getSkuList();
        productRequest.setStoreInfo(europeProductSku.get(0).getComposition());
        productRequest.setContent(europeProductSku.get(0).getComposition());
        productRequest.setStoreName(europeProduct.getGoodsName());
        if(null != storeBrand) {
            productRequest.setBrandId(storeBrand.getId());
            productRequest.setBrandName(storeBrand.getEnName());
        }
        productRequest.setPrice(adjustPrice);
        productRequest.setOtPrice(referencePrice);
        productRequest.setCost(adjustcost);

        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.EUROPE)
                .eq(CategoryMatch :: getOthCategoryId, europeProduct.getCategoryId())
                .eq(CategoryMatch :: getOthCategoryType, europeProduct.getTypeId())
                .last("LIMIT 1")
                );
        // 复制重量
        if(null != categoryMatch) {
        	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
        	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
        }
        if(null != categoryMatch) {
            productRequest.setCateId(categoryMatch.getCategoryId());
            productRequest.setCateIds(Arrays.asList(categoryMatch.getCategoryId()));
        }
        productRequest.setImage(europeProduct.getGoodsImg());
        // 商品图片
        if (StringUtil.isNotEmpty(europeProduct.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(europeProduct.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (!CollectionUtils.isEmpty(arr)) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSpecType(true);
        // 发货地欧洲
        productRequest.setTempId(3);
        productRequest.setUnitName("件");
        // 是否代理商
        if (null != europeProduct.getSupplierId() && SuppliersIdEnum.EASY_FASHION.getCode().equals(europeProduct.getSupplierId() + "")) {
            productRequest.setMerUse(true);
        }
        productRequest.setSourceCost(price);
        
        //供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getSuppliersName, "1MAG")
                .last("LIMIT 1")
                );
        if(null != supplier && !StringUtil.isEmpty(supplier.getBarcode())) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
            productRequest.setBarCode(supplier.getBarcode() + europeProduct.getGoodId());
        } else {
            productRequest.setBarCode(BarCodeEnum.EUROPE.getCode().toString() + europeProduct.getGoodId());
        }
        productRequest.setIsEurope(ProductTypeEnum.EUROPE.getCode());
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        productRequest.setLastPushTime(new Date());
        return productRequest;
    }
    
    /**
     * 欧洲商品构建（多商户版本方法）
     * @Description:  
     * @author daigb 
     * @param @param europeProduct
     * @param @return
     * @return StoreProductCrmebRequest
     * @throws
     */
    public StoreProductCrmebRequest buildEuropeProduct(EuropeProduct europeProduct, Map<String, EuropeBrand> europeBrandMap) {
    	PriceResult priceResult = priceUtil.eur2Rmb(europeProduct.getPrice());
        BigDecimal price = priceResult.getPrice();
//        BigDecimal adjustPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(PriceUtil.eur2Rmb(price)), rate);
        BigDecimal adjustPrice = price;
//        BigDecimal adjustcost = PriceUtil.calePrice(PriceUtil.eur2Rmb(price), rateCost);
        BigDecimal adjustcost = price;
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, europeProduct.getBrandId())
                .eq(StoreBrand :: getType, ProductTypeEnum.EUROPE)
                .last("LIMIT 1")
                );
        storeBrandService.unMatchBrand(buyerStoreBrand,europeProduct.getBrandId().toString(),null,ProductTypeEnum.EUROPE);
        StoreBrand storeBrand = null;
        if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }else {
            storeBrand = storeBrandService.getById(5429);
        }
        // 处理单独品牌价格(无法做成配置的)
        if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
            adjustPrice = PriceUtil.calePrice(priceUtil.eur2Rmb(price).getPrice(), "0.65");
        }
        
        List<EuropeProductSkuMerged> list = europeProduct.getSkuMergedList();
        // 规格处理
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);
        
        BigDecimal referencePrice = europeProduct.getReferencePrice();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();
        
        List<String> valueList = new ArrayList<>();
        List<String> valueColorList = new ArrayList<>();
        
        for(EuropeProductSkuMerged esm : list) {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setImage(europeProduct.getGoodsImg());
            storeProductAttrValueRequest.setPrice(adjustPrice);
            storeProductAttrValueRequest.setOtPrice(referencePrice);
            storeProductAttrValueRequest.setCost(adjustcost);
            storeProductAttrValueRequest.setSourceCost(adjustcost);
            storeProductAttrValueRequest.setStock(esm.getStock());
            storeProductAttrValueRequest.setSourceSkuId(esm.getSkuId());
            
            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            List<String> suk = new ArrayList<String>();
            if (StringUtils.isNotBlank(esm.getColor())) {
                linkedMap.put("颜色", esm.getColor());
                if (!valueColorList.contains(esm.getColor())) {
                    valueColorList.add(esm.getColor());
                }
                suk.add(esm.getColor());
            }
            if (StringUtils.isNotBlank(esm.getSize())) {
                linkedMap.put("尺寸", esm.getSize());
                if (!valueList.contains(esm.getSize())) {
                    valueList.add(esm.getSize());
                }
                suk.add(esm.getSize());
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        }
        if (CollectionUtils.isNotEmpty(valueColorList)) {
            storeProductAttrColor.setAttrValues(String.join(",", valueColorList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }
        
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        productRequest.setExchangeRate(priceResult.getExchangeRate());
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        productRequest.setMerId(CrmebMerchantEnums.EUROPE.getMerchantId());
        productRequest.setContent(europeProduct.getGoodsName());
        productRequest.setKeyword(europeProduct.getCode());
        List<EuropeProductSku> europeProductSku = europeProduct.getSkuList();
        productRequest.setStoreInfo(europeProductSku.get(0).getComposition());
        productRequest.setStoreName(europeProduct.getGoodsName());
        if(null != storeBrand) {
            productRequest.setBrandId(storeBrand.getId());
            productRequest.setBrandName(storeBrand.getEnName());
        }
        productRequest.setPrice(adjustPrice);
        productRequest.setOtPrice(referencePrice);
        productRequest.setCost(adjustcost);
        
        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.EUROPE)
                .eq(CategoryMatch :: getOthCategoryId, europeProduct.getCategoryId())
                .eq(CategoryMatch :: getOthCategoryType, europeProduct.getTypeId())
                .last("LIMIT 1")
                );
        categoryMatchService.unMatchCategory(categoryMatch,europeProduct.getCategoryId().toString(),europeProduct.getTypeId().toString(),null,CategoryTypeEnum.EUROPE);
        if(null != categoryMatch) {
            productRequest.setCateId(categoryMatch.getCategoryId());
            productRequest.setCateIds(Arrays.asList(categoryMatch.getCategoryId()));
        }
        productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
        productRequest.setImage(europeProduct.getGoodsImg());
        // 商品图片
        if (StringUtil.isNotEmpty(europeProduct.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(europeProduct.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (!CollectionUtils.isEmpty(arr)) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSpecType(true);
        // 发货地欧洲
        productRequest.setTempId(3);
        productRequest.setUnitName("件");
        // 是否代理商
        if (null != europeProduct.getSupplierId() && SuppliersIdEnum.EASY_FASHION.getCode().equals(europeProduct.getSupplierId() + "")) {
            productRequest.setMerUse(true);
        }
        productRequest.setSourceCost(price);
        
        //供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getSuppliersName, "1MAG")
                .last("LIMIT 1")
                );
        if(null != supplier && !StringUtil.isEmpty(supplier.getBarcode())) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
            productRequest.setBarCode(supplier.getBarcode() + europeProduct.getGoodId());
        } else {
            productRequest.setBarCode(BarCodeEnum.EUROPE.getCode().toString() + europeProduct.getGoodId());
        }
        productRequest.setIsEurope(ProductTypeEnum.EUROPE.getCode());
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        productRequest.setLastPushTime(new Date());
        return productRequest;
    }
    
}
